﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace Training11
{
    internal class MySqlOperate
    {
        private string MySqlConnectionString;

        public MySqlOperate()
        {
            MySqlConnectionString="server=127.0.0.1;database=bms;username=root;password=jimmy;";
        }

        public void Open(MySqlConnection cnn)
        {
            if (cnn.State == System.Data.ConnectionState.Closed)
            {
                cnn.Open();
            }
        }

        public void Close(MySqlConnection cnn)
        {
            if (cnn != null)
            {
                if (cnn.State == ConnectionState.Open)
                {
                    cnn.Close();
                }
                cnn.Dispose();
            }
        }
        public MySqlDataReader GetDR(string strSql)
        {
            MySqlConnection cnn = new MySqlConnection(MySqlConnectionString);
            MySqlCommand cmd;
            try
            {
                Open(cnn);
                cmd = new MySqlCommand(strSql, cnn);
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                //cmd.Dispose();
            }
        }

        public DataSet GetDS(string strSql)
        {
            MySqlConnection cnn = new MySqlConnection(MySqlConnectionString);
            MySqlDataAdapter sda = new MySqlDataAdapter();
            try
            {
                Open(cnn);
                sda = new MySqlDataAdapter(strSql, cnn);
                DataSet ds = new DataSet();
                sda.Fill(ds);
                return ds;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                sda.Dispose();
                Close(cnn);
            }
        }

        public int RunSql(string strSql)
        {
            MySqlConnection cnn = new MySqlConnection(MySqlConnectionString);
            MySqlCommand cmd = new MySqlCommand();
            try
            {
                Open(cnn);
                cmd = new MySqlCommand(strSql, cnn);
                return cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                cmd.Dispose();
                Close(cnn);
            }
        }


    }
}
